<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref, defineProps } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { BasicForm, useForm } from '@/components/Form'
import { getOrganizationTree } from '@/api/sys/dept'
import { addMonthLossAdd } from '@/api/sys/user'
defineOptions({ name: 'AccountModal' })
const props = defineProps({
  dictCode: {
    type: String,
    default: 'energy_type'
  },
  title: {
    type: String,
    default: 'B4月类COP'
  }
})
const emit = defineEmits(['success', 'register'])

const isUpdate = ref(true)
const rowId = ref('')

const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: [
    {
      field: 'month',
      label: '月份',
      component: 'MonthPicker',
      rules: [
        {
          required: true,
          message: '请输入月份',
        },
      
      ],
    },
    {
      field: 'val',
      label: props.title,
      component: 'Input',
      rules: [
        {
          required: true,
          message: `请输入${props.title}`,
        },
      ],
    },
  ],
  showActionButtonGroup: false,
  actionColOptions: {
    span: 23,
  },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields()
  setModalProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate

  if (unref(isUpdate)) {
    rowId.value = data.record.userId
    setFieldsValue({
      ...data.record,
    })
  }

  const treeData = await getOrganizationTree()
  updateSchema([
    {
      field: 'orgId',
      componentProps: { treeData },
    },
  ])
})

const getTitle = computed(() => (!unref(isUpdate) ? props.title : '编辑用户'))

async function handleSubmit() {
  try {
    const values = await validate()
    setModalProps({ confirmLoading: true })
    const params: any = { ...values }

    params.month = params.month.split('-').slice(0, 2).join('-');
    console.log(params, "???");
    params.type = props.dictCode
    params.checkMonth = false
    const res = await addMonthLossAdd(params)
    !res && closeModal()
    closeModal()
    emit('success', { isUpdate: unref(isUpdate), values: { ...values } })
  } finally {
    setModalProps({ confirmLoading: false })
  }
}

</script>
